package demo1.Panels;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class MyPicture extends JPanel {
    BufferedImage image;
    public MyPicture() {
        try {
            File file = new File("data/picture/cg.png");
            this.image = ImageIO.read(file);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int width = this.getWidth();
        int height = this.getHeight();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,width,height);

        //动态保持长宽比
        int imgW = image.getWidth();
        int imgH = image.getHeight();
        int fitW = width;
        int fitH = fitW * imgH / imgW;
        if(fitH > height) {
            fitH = height;
            fitW = fitH * imgW / imgH;
        }
        int fitX = (width - fitW) / 2;
        int fitY = (height - fitH) / 2;

        g.drawImage(image,fitX,fitY,fitW,fitH,null);
    }
}
